"use strict"
const fs = require("fs")
const Nls = require("alibabacloud-nls")
const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs))


async function runOnce(line) {
    let dumpFile = fs.createWriteStream(`${process.pid}.wav`, { flags: "w" })
    const config = {
        accessKeyId: 'LTAI5tMZaTKp3tkiCoZWaqzN',
        accessKeySecret: 'mpn9Y3TGWorEI1ZbvusP8fkotmUUy9',
        url: 'wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1',
        appkey: 'B4CLnDz6EYmy6kGq',
        token: 'e9e025a0ac56452a9d5db59e58befe96'
    };

    let tts = new Nls.SpeechSynthesizer({
        url: config.url,
        appkey: config.appkey,
        token: config.token
    })

    tts.on("meta", (msg) => {
        console.log("Client recv metainfo:", msg)
    })

    tts.on("data", (msg) => {
        console.log(`recv size: ${msg.length}`)
        console.log(dumpFile.write(msg, "binary"))
    })

    tts.on("completed", (msg) => {
        console.log("Client recv completed:", msg)
    })

    tts.on("closed", () => {
        console.log("Client recv closed")
    })

    tts.on("failed", (msg) => {
        console.log("Client recv failed:", msg)
    })

    let param = tts.defaultStartParams()
    // 待合成文本
    param.text = line
    // 发音人
    // param.voice = "xiaoyun"
    // 语调，范围是-500~500，可选，默认是0
    // param.pitch_rate = 100
    // 语速，范围是-500~500，默认是0
    // param.speech_rate = 100
    // 设置返回音频的编码格式
    // param.format = "wav"
    // 设置返回音频的采样率
    // param.sample_rate = 16000
    // 是否开启字级别时间戳
    // param.enable_subtitle = true
    try {
        await tts.start(param, true, 6000)
    } catch (error) {
        console.log("error on start:", error)
        return
    } finally {
        dumpFile.end()
    }
    console.log("synthesis done")
    await sleep(2000)
}

async function test() {
    await runOnce('一句话识别、录音文件识别、录音文件识别闲时版、语音合成、长文本语音合成')
}

test()